package com.example.quartzdemo.init;

import com.example.quartzdemo.Entity.QuartzBean;
import com.example.quartzdemo.constans.BaseConstant;
import com.example.quartzdemo.memory.CacheFactory;
import com.example.quartzdemo.memory.LocalCache;
import com.example.quartzdemo.memory.LocalCacheTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * @author yeyangtao
 * @since 2022/6/20 16:28
 */
@Slf4j
@Component
public class JobInit implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        List<QuartzBean> jobs;
        Resource resource = new ClassPathResource(BaseConstant.BACKUP_PATH);

        try (FileInputStream fis = new FileInputStream(resource.getFile().getPath());
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            jobs = (List<QuartzBean>) ois.readObject();
            for (QuartzBean q : jobs) {
                LocalCache localCache = CacheFactory.getLocalCache(LocalCacheTypeEnum.LIST);
                boolean success = localCache.add(q);
                if (!success) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("初始化结束");
    }
}
